<template>
    <div ref="dom" class="chart" />
</template>

<script setup lang="ts">
import type {Ref}                                                                                                from 'vue'
import {defineProps, onActivated, reactive, ref, watch}                                                          from 'vue'
import {useEventListener}                                                                                        from '@vueuse/core'
import * as echarts                                                                                              from 'echarts/core'
import {CanvasRenderer}                                                                                          from 'echarts/renderers'
import {LineChart}                                                                                               from 'echarts/charts'
import {DataZoomComponent, GridComponent, MarkAreaComponent, TitleComponent, ToolboxComponent, TooltipComponent} from 'echarts/components'
import {UniversalTransition}                                                                                     from "echarts/features";
import {statistics as getStatistics}                                                                             from "@/api/garden";
import moment                                                                                                    from "moment";

const props = defineProps({
    gardenId: String
})

watch(() => props.gardenId, (newVal) => {
    queryParam.gardenId = newVal
    loadData()
})

const dom: Ref<HTMLDivElement> = ref(null) as any

let myEchart: echarts.ECharts | null = null

// 使用Echart
function useEchart() {
    return new Promise((resolve) => {
        echarts.use([
            TitleComponent, ToolboxComponent, TooltipComponent,
            GridComponent, DataZoomComponent, LineChart,
            CanvasRenderer, UniversalTransition, MarkAreaComponent
        ]);
        myEchart = echarts.init(dom.value)
        useEventListener("resize", () => myEchart!.resize())
        resolve("ok")
    })
}

// 原始数据
const sourceMap: any = ref({
    allCount: {}, // 每个站点的统计数

    weekAreaList    : [], // 周异常区域
    weekAllCountList: [], // 每周 所有站点的数据
})

const queryParam: any = reactive({
    gardenId : null,
    startDate: moment().subtract(2, "years"),
    endDate  : null,
    dayMode  : false,
})

// 加载数据
function loadData() {
    return new Promise((resolve) => {
        getStatistics(queryParam).then(res => {
            sourceMap.value = res?.data
        }).then(dealArr).then(draw).then(resolve)
    })
}

// 缓存的周数据
const weekShow: any = {
    xKey    : [],
    xdata   : [],
    areaData: [],
}

// 缓存数据
function dealArr() {
    return new Promise((resolve) => {
        weekShow.areaData = sourceMap.value.weekAreaList
        weekShow.xKey     = sourceMap.value.weekAllCountList.map((one: any) => one.weekEnd)
        weekShow.xdata    = sourceMap.value.weekAllCountList.map((one: any) => {
            if (one.isAnomaly) {
                one.symbol     = "circle"
                one.symbolSize = 10
                one.itemStyle  = {
                    color: "#ff0000",
                }
            }
            return one
        })
        resolve("ok")
    })
}

// 图标参数
const options = {
    tooltip: {
        trigger : 'axis',
        position: function (pt: any) {
            return [pt[0], '10%'];
        }
    },

    toolbox : {
        feature: {
            dataZoom   : {
                yAxisIndex: 'none'
            },
            restore    : {},
            saveAsImage: {}
        }
    },
    xAxis   : {
        type       : 'category',
        boundaryGap: false,
        axisLabel  : {},
        data       : [] // 横坐标
    },
    yAxis   : {
        type       : 'value',
        alignTicks : true,
        boundaryGap: [0, '100%'],
        max        : 'dataMax', //取最大值为最大刻度
    },
    dataZoom: [
        {
            type : 'inside',
            start: 0,
            end  : 100
        },
        {
            start: 0,
            end  : 20
        }
    ],
    series  : [
        {
            name         : "",
            showAllSymbol: true,
            type         : 'line',
            smooth       : false,
            symbol       : 'none',
            data         : [],
            markArea     : {
                itemStyle: {
                    color: 'rgba(255, 173, 177, 0.4)'
                },
                data     : []
            }
        }
    ]
}


// 绘图
function draw() {
    return new Promise((resolve) => {
        options.xAxis.data              = weekShow.xKey
        options.series[0].data          = weekShow.xdata
        options.series[0].markArea.data = weekShow.areaData

        myEchart?.setOption(options, true)
        resolve("ok")
    })
}


// --------------------------- 生命函数 ---------------------------
onActivated(() => {
    useEchart().then(loadData)
})

</script>

<style lang="scss" scoped>
.chart {
    width: 100%;
    height: 100%;
    background: #fff;
    box-sizing: border-box;
    display: flex;
    justify-content: center;
}
</style>
